
package com.jf.cloud.order.controller.app;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import com.jf.cloud.api.delivery.feign.DeliveryFeignClient;
import com.jf.cloud.api.delivery.vo.DeliveryOrderFeignVO;
import com.jf.cloud.api.feign.EsOrderFeignClient;
import com.jf.cloud.api.multishop.feign.ShopDetailFeignClient;
import com.jf.cloud.api.multishop.vo.ShopDetailVO;
import com.jf.cloud.api.order.constant.OrderDeleteStatus;
import com.jf.cloud.api.order.constant.OrderStatus;
import com.jf.cloud.common.order.bo.EsOrderBO;
import com.jf.cloud.common.order.vo.*;
import com.jf.cloud.api.vo.EsPageVO;
import com.jf.cloud.common.constant.Constant;
import com.jf.cloud.common.database.dto.PageDTO;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.order.constant.DeliveryType;
import com.jf.cloud.common.order.constant.OrderActivityType;
import com.jf.cloud.common.order.dto.OrderSearchDTO;
import com.jf.cloud.common.product.constant.PreSaleType;
import com.jf.cloud.common.response.ResponseEnum;
import com.jf.cloud.common.response.ServerResponseEntity;
import com.jf.cloud.common.rocketmq.config.RocketMqConstant;
import com.jf.cloud.common.security.AuthUserContext;
import com.jf.cloud.common.util.Arith;
import com.jf.cloud.order.constant.RefundStatusEnum;
import com.jf.cloud.order.constant.RefundType;
import com.jf.cloud.order.model.Order;
import com.jf.cloud.order.model.OrderAddr;
import com.jf.cloud.order.model.OrderItem;
import com.jf.cloud.order.service.*;
import com.jf.cloud.order.vo.OrderRefundVO;
import com.jf.cloud.order.vo.OrderShopVO;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;
import ma.glasnost.orika.MapperFacade;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 我的订单
 *
 * @author zz
 */
@RestController
@RequestMapping("/my_order")
@Tag(name = "app-我的订单接口")
public class MyOrderController {
    private final Logger LOGGER = LoggerFactory.getLogger(MyOrderController.class);

    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderPreSaleInfoService orderPreSaleInfoService;
    @Autowired
    private MapperFacade mapperFacade;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private OrderRefundService orderRefundService;
    @Autowired
    private OrderAddrService orderAddrService;
    @Autowired
    private RocketMQTemplate orderReceiptTemplate;
    @Autowired
    private DeliveryFeignClient deliveryFeignClient;
    @Autowired
    private EsOrderFeignClient esOrderFeignClient;
    @Autowired
    private ShopDetailFeignClient shopDetailFeignClient;
    @Autowired
    private OrderVirtualInfoService orderVirtualInfoService;

    /**
     * 订单详情信息接口
     */
    @GetMapping("/order_detail")
    @Operation(summary = "订单详情信息" , description = "根据订单号获取订单详情信息")
    @Parameter(name = "orderId", description = "订单号" , required = true)
    public ServerResponseEntity<OrderShopVO> orderDetail(@ParameterObject @RequestParam(value = "orderId") Long orderId) {

        Long userId = AuthUserContext.get().getUserId();
        Long stationId = AuthUserContext.get().getTenantId();
        OrderShopVO orderShopDto = new OrderShopVO();
        Order order;
        if(Objects.isNull(stationId)){
            LOGGER.info("非自提订单，用户id：{}，订单号：{}", userId, orderId);
            order = orderService.getOrderByOrderIdAndUserId(orderId, userId);
        }else{
            LOGGER.info("自提订单，用户id：{}，订单号：{}，站点id：{}", userId, orderId, stationId);
            order = orderService.getOrderByOrderIdAndStationId(orderId, stationId);
        }
        if (Objects.equals(order.getShopId(), Constant.PLATFORM_SHOP_ID)) {
            order.setShopName(Constant.PLATFORM_SHOP_NAME);
        }
        // 套餐优惠加到“促销满减”字段中
        if(Objects.nonNull(order.getShopComboAmount())){
            order.setDiscountAmount(order.getShopComboAmount() + order.getDiscountAmount());
        }
        OrderAddr orderAddr = orderAddrService.getById(order.getOrderAddrId());

        List<OrderItemVO> orderItems = orderItemService.listOrderItemAndLangByOrderId(orderId);

        setOrderShopDto(orderShopDto, order, orderAddr, orderItems);

        List<OrderRefundVO> orderRefunds = orderRefundService.getProcessingOrderRefundByOrderId(order.getOrderId());
        long alreadyRefundAmount = 0L;
        for (OrderRefundVO orderRefund : orderRefunds) {
            alreadyRefundAmount = alreadyRefundAmount + orderRefund.getRefundAmount();
            // 整单退款
            if (Objects.equals(RefundType.ALL.value(),orderRefund.getRefundType())) {
                orderShopDto.setCanRefund(false);
                // 统一的退款单号
                for (OrderItemVO orderItemDto : orderItems) {
                    orderItemDto.setFinalRefundId(orderRefund.getRefundId());
                }
                break;
            }
            // 单项退款，每个单号都不一样
            for (OrderItemVO orderItemDto : orderItems) {
                if (Objects.equals(orderItemDto.getOrderItemId(), orderRefund.getOrderItemId())) {
                    orderItemDto.setFinalRefundId(orderRefund.getRefundId());
                }
            }

        }
        orderShopDto.setCanRefundAmount(order.getActualTotal()-alreadyRefundAmount);
        if (order.getRefundStatus() != null && !Objects.equals(order.getRefundStatus(), RefundStatusEnum.DISAGREE.value())) {
            orderShopDto.setFinalRefundId(orderItems.get(0).getFinalRefundId());
        }
        // 若订单为未支付状态，补充上订单自动取消时间
        if (Objects.equals(orderShopDto.getStatus(), OrderStatus.UNPAY.value())) {
            orderShopDto.setAutoCancelTime(new Date(orderShopDto.getCreateTime().getTime() + RocketMqConstant.CANCEL_TIME_INTERVAL));
        }
        // 处理虚拟订单
        if(Objects.equals(order.getOrderMold(),1)) {
            LOGGER.info("处理虚拟订单，订单号：{}", order.getOrderId());
            List<OrderItem> orderItemList = mapperFacade.mapAsList(orderItems, OrderItem.class);
            order.setOrderItems(orderItemList);
            orderVirtualInfoService.handlerVirtualProdOrder(order, orderShopDto, stationId);
        }
        return ServerResponseEntity.success(orderShopDto);
    }

    /**
     * 插入数据
     * @param orderShopDto 插入对象
     * @param order 订单信息
     * @param orderAddr 订单地址
     * @param orderItems 订单项列表
     */
    private void setOrderShopDto(OrderShopVO orderShopDto, Order order, OrderAddr orderAddr, List<OrderItemVO> orderItems) {
        // 处理下发货完成时能否查看物流
        int updateOrViewDeliveryInfo = 0;
        if (!Objects.equals(order.getDeliveryType(), DeliveryType.DELIVERY.value())) {
            orderShopDto.setUpdateOrViewDeliveryInfo(updateOrViewDeliveryInfo);
        }
        for (OrderItemVO orderItem : orderItems) {
            if (Objects.nonNull(orderItem.getDeliveryType()) && Objects.equals(orderItem.getDeliveryType(), DeliveryType.DELIVERY.value())) {
                updateOrViewDeliveryInfo = 1;
                break;
            }
        }
        getOrderShop(orderShopDto, order, orderAddr, updateOrViewDeliveryInfo);
        // 处理退款
        handleRefund(orderShopDto, order, orderItems);
        orderShopDto.setOrderItems(orderItems);
        // 处理赠品订单项
        List<OrderItemVO> orderItemList = orderItems.stream()
                .filter(item -> Objects.equals(item.getMainGiveaway(), 1))
                .collect(Collectors.toList());

        orderShopDto.setTotal(order.getTotal());
        orderShopDto.setTotalNum(order.getAllCount());
        // 预售订单获取预售信息
        if (Objects.nonNull(order.getPreSaleType()) && !Objects.equals(order.getPreSaleType(), PreSaleType.DISABLE.value())) {
            OrderPreSaleInfoVO orderPreSaleInfo = orderPreSaleInfoService.getByOrderId(order.getOrderId());
            orderShopDto.setPayTime(Objects.equals(orderPreSaleInfo.getPreSaleType(), PreSaleType.DEPOSIT.value()) && Objects.equals(orderPreSaleInfo.getPayStatus(), 2) ? orderPreSaleInfo.getBalancePayTime() : order.getPayTime());
            orderShopDto.setOrderPreSaleInfoVO(orderPreSaleInfo);
        }
        if (CollUtil.isEmpty(orderItemList)) {
            return;
        }

        Long total = 0L;
        Integer totalNum = 0;
        Map<Long, List<OrderItemVO>> giveawayMap = orderItems.stream()
                .filter(item -> Objects.equals(item.getActivityType(), OrderActivityType.GIVEAWAY.value()))
                .collect(Collectors.groupingBy(OrderItemVO::getActivityId));
        for (OrderItemVO orderItem : orderItemList) {
            total += orderItem.getSpuTotalAmount();
            totalNum += orderItem.getCount();
            // 放入赠品
            if (giveawayMap.containsKey(orderItem.getOrderItemId())) {
                orderItem.setGiveawayList(giveawayMap.get(orderItem.getOrderItemId()));
            }
        }
        List<OrderItemVO> orderItemVOList = orderItems.stream()
                .filter(item -> Objects.equals(item.getMainGiveaway(), null))
                .collect(Collectors.toList());
        orderItemList.addAll(orderItemVOList);
        orderShopDto.setOrderItems(orderItemList);
        orderShopDto.setTotal(total);
        orderShopDto.setTotalNum(totalNum);
        orderShopDto.setShopComboAmount(order.getShopComboAmount());
    }

    private void getOrderShop(OrderShopVO orderShopDto, Order order, OrderAddr orderAddr, int updateOrViewDeliveryInfo) {
        orderShopDto.setUpdateOrViewDeliveryInfo(updateOrViewDeliveryInfo);
        orderShopDto.setOrderScore(order.getOrderScore());
        orderShopDto.setShopId(order.getShopId());
        orderShopDto.setDeliveryType(order.getDeliveryType());
        orderShopDto.setShopName(order.getShopName());
        orderShopDto.setActualTotal(order.getActualTotal());
        orderShopDto.setOrderAddr(mapperFacade.map(orderAddr, OrderAddrVO.class));
        orderShopDto.setPayType(order.getPayType());
        orderShopDto.setTransfee(order.getFreightAmount());
        orderShopDto.setReduceAmount(Math.abs(order.getReduceAmount()));
        orderShopDto.setCreateTime(order.getCreateTime());
        orderShopDto.setRemarks(order.getRemarks());
        orderShopDto.setOrderType(order.getOrderType());
        orderShopDto.setStatus(order.getStatus());
        // 返回满减优惠金额，优惠券优惠金额和店铺优惠总额
        orderShopDto.setDiscountMoney(order.getDiscountAmount());
        orderShopDto.setShopCouponMoney(order.getShopCouponAmount());
        orderShopDto.setFreeFreightAmount(order.getFreeFreightAmount());
        double shopAmount = Arith.sub(Arith.sub(order.getReduceAmount(), order.getPlatformAmount()), order.getShopChangeFreeAmount());
        orderShopDto.setShopAmount(new Double(shopAmount).longValue());
        //返回平台优惠券，平台等级，平台积分优惠金额和平台免运费金额
        orderShopDto.setPlatformCouponAmount(order.getPlatformCouponAmount());
        orderShopDto.setMemberAmount(order.getMemberAmount());
        orderShopDto.setScoreAmount(order.getScoreAmount());
        orderShopDto.setPlatformFreeFreightAmount(order.getPlatformFreeFreightAmount());
        orderShopDto.setShopChangeFreeAmount(order.getShopChangeFreeAmount());
        // 付款时间
        orderShopDto.setPayTime(order.getPayTime());
        // 发货时间
        orderShopDto.setDeliveryTime(order.getDeliveryTime());
        // 完成时间
        orderShopDto.setFinallyTime(order.getFinallyTime());
        // 取消时间
        orderShopDto.setCancelTime(order.getCancelTime());
        // 更新时间
        orderShopDto.setUpdateTime(order.getUpdateTime());
        //订单发票id
        orderShopDto.setOrderInvoiceId(order.getOrderInvoiceId());
        orderShopDto.setOrderMold(order.getOrderMold());
        orderShopDto.setPreSaleType(order.getPreSaleType());
    }

    private void handleRefund(OrderShopVO orderShopDto, Order order, List<OrderItemVO> orderItems) {
        // 可以退款的状态，并在退款时间内
        if (order.getStatus() > OrderStatus.UNPAY.value() && order.getStatus() < OrderStatus.CLOSE.value() && orderRefundService.checkRefundDate(order)) {
            LOGGER.info("订单{}可以退款", order.getOrderId());
            orderShopDto.setCanRefund(true);
            orderShopDto.setCanAllRefund(true);
            for (OrderItemVO orderItem : orderItems) {
                // 有正在退款中的订单项
                if (orderItem.getRefundStatus() != null && !Objects.equals(orderItem.getRefundStatus(), RefundStatusEnum.DISAGREE.value())) {
                    // 无法整单退款
                    orderShopDto.setCanAllRefund(false);
                }
                // 如果是虚拟商品订单，处理下虚拟商品订单相关数据
                if (Objects.equals(orderItem.getIsRefund(), 0)) {
                    orderShopDto.setCanAllRefund(false);
                    orderShopDto.setCanRefund(false);
                }
            }
            // 正在进行整单退款
            if (order.getRefundStatus() != null && !Objects.equals(order.getRefundStatus(), RefundStatusEnum.DISAGREE.value())) {
                // 所有订单项都没办法退款
                orderShopDto.setCanAllRefund(false);
            }
        }
        if (Objects.nonNull(order.getRefundStatus()) && !Objects.equals(order.getRefundStatus(), RefundStatusEnum.DISAGREE.value())) {
            List<OrderRefundVO> refundVOList = orderRefundService.getProcessingOrderRefundByOrderId(order.getOrderId());
            for (OrderRefundVO orderRefund : refundVOList) {
                //整单退款
                if (orderRefund.getRefundType() == 1) {
                    for (OrderItemVO orderItem : orderItems) {
                        orderItem.setReturnMoneySts(orderRefund.getReturnMoneySts());
                    }
                    break;
                }
                // 单项退款，每个单号都不一样
                for (OrderItemVO orderItem : orderItems) {
                    if (Objects.equals(orderItem.getOrderItemId(), orderRefund.getOrderItemId())) {
                        orderItem.setReturnMoneySts(orderRefund.getReturnMoneySts());
                    }
                }
            }
        }
    }

    @GetMapping("/order_count")
    @Operation(summary = "计算各个订单数量" , description = "根据订单状态计算各个订单数量")
    public ServerResponseEntity<OrderCountVO> orderCount() {
        Long userId = AuthUserContext.get().getUserId();
        OrderCountVO orderCount = orderService.countNumberOfStatus(userId);
        return ServerResponseEntity.success(orderCount);
    }

    /**
     * 分页获取
     */
    @GetMapping("/search_order")
    @Operation(summary = "订单列表信息查询" , description = "根据订单编号或者订单中商品名称搜索")
    public ServerResponseEntity<EsPageVO<EsOrderVO>> searchOrder(@ParameterObject OrderSearchDTO orderSearchDTO) {
        Long userId = AuthUserContext.get().getUserId();
        orderSearchDTO.setUserId(userId);
        orderSearchDTO.setShopId(orderSearchDTO.getShopId());
        orderSearchDTO.setDeleteStatus(0);
        EsPageVO<EsOrderVO> esOrderPageVO = orderService.myOrderPage(orderSearchDTO);
        List<EsOrderVO> orderList = esOrderPageVO.getList();

        // 店铺名称
        if (CollUtil.isNotEmpty(orderList)){
            List<Long> shopIdList = orderList.stream().map(EsOrderVO::getShopId).collect(Collectors.toList());
            List<ShopDetailVO> shopDetailVOList = shopDetailFeignClient.listByShopIds(shopIdList).getData();
            Map<Long, List<ShopDetailVO>> shopDetailVoMap = shopDetailVOList.stream().collect(Collectors.groupingBy(ShopDetailVO::getShopId));
            for (EsOrderVO esOrderVO : orderList) {
                if (Objects.equals(esOrderVO.getShopId(), Constant.PLATFORM_SHOP_ID)) {
                    esOrderVO.setShopName(Constant.PLATFORM_SHOP_NAME);
                } else if (shopDetailVoMap.containsKey(esOrderVO.getShopId())) {
                    esOrderVO.setShopName(shopDetailVoMap.get(esOrderVO.getShopId()).get(0).getShopName());
                }
            }
        }

        boolean checkDeliveryNum = Objects.equals(orderSearchDTO.getStatus(), OrderStatus.PAYED.value()) || Objects.isNull(orderSearchDTO.getStatus());
        Map<Long, Integer> deliveryCountMap = new HashMap<>(16);
        if (checkDeliveryNum) {
            List<Long> orderIds = orderList.stream().map(EsOrderVO::getOrderId).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(orderIds)) {
                ServerResponseEntity<List<DeliveryOrderFeignVO>> responseEntity = deliveryFeignClient.listDeliveryCountByOrderIds(orderIds);
                if (responseEntity.isFail()) {
                    throw new LuckException(responseEntity.getMsg());
                }
                List<DeliveryOrderFeignVO> deliveryOrderList = responseEntity.getData();
                deliveryCountMap = deliveryOrderList.stream().collect(Collectors.toMap(DeliveryOrderFeignVO::getOrderId, DeliveryOrderFeignVO::getAllCount));
            }
        }
        // 处理下发货完成时能否查看物流
        for (EsOrderVO esOrderVO : orderList) {
            if (Objects.equals(esOrderVO.getShopId(), Constant.PLATFORM_SHOP_ID)) {
                esOrderVO.setShopName(Constant.PLATFORM_SHOP_NAME);
            }
            int updateOrViewDeliveryInfo = 0;
            if(!Objects.equals(esOrderVO.getDeliveryType(), DeliveryType.DELIVERY.value())){
                esOrderVO.setUpdateOrViewDeliveryInfo(updateOrViewDeliveryInfo);
                continue;
            }
            for (EsOrderItemVO orderItem : esOrderVO.getOrderItems()) {
                if(Objects.nonNull(orderItem.getDeliveryType()) && Objects.equals(orderItem.getDeliveryType(),DeliveryType.DELIVERY.value())){
                    updateOrViewDeliveryInfo = 1;
                    break;
                }
            }
            if (checkDeliveryNum) {
                if (deliveryCountMap.containsKey(esOrderVO.getOrderId())) {
                    esOrderVO.setDeliveryCount(deliveryCountMap.get(esOrderVO.getOrderId()));
                }
            }
            esOrderVO.setUpdateOrViewDeliveryInfo(updateOrViewDeliveryInfo);
        }


        for(EsOrderVO orderVO : orderList){
            Map<Long, List<EsOrderItemVO>> map = orderVO.getOrderItems().stream()
                    .filter(s -> Objects.equals(s.getActivityType(), OrderActivityType.GIVEAWAY.value()))
                    .collect(Collectors.groupingBy(EsOrderItemVO::getActivityId));
            // 如果没有赠品，就不需要处理
            if (MapUtil.isEmpty(map)) {
                continue;
            }
            // 将赠品放到对应的主订单项中
            Iterator<EsOrderItemVO> iterator = orderVO.getOrderItems().iterator();
            while (iterator.hasNext()) {
                EsOrderItemVO myOrderItemDto = iterator.next();
                // 移除赠品的订单项，进入下一个循环
                if (Objects.equals(myOrderItemDto.getActivityType(), OrderActivityType.GIVEAWAY.value())) {
                    iterator.remove();
                    continue;
                }
                // 主订单项插入赠品订单项
                if (map.containsKey(myOrderItemDto.getOrderItemId())) {
                    myOrderItemDto.setGiveawayList(map.get(myOrderItemDto.getOrderItemId()));
                }
            }
        }
        return ServerResponseEntity.success(esOrderPageVO);
    }

    // todo 定时任务将订单项设为不可评论的状态
    /**
     * 订单评价列表接口
     */
    @GetMapping("/search_order_item")
    @Operation(summary = "订单评价列表接口" , description = "根据订单评价状态获取订单列表信息")
    public ServerResponseEntity<EsPageVO<EsOrderVO>> searchOrderItem(PageDTO page) {

        OrderSearchDTO orderSearchDTO = new OrderSearchDTO();
        Long userId = AuthUserContext.get().getUserId();
        orderSearchDTO.setUserId(userId);
        orderSearchDTO.setPageNum(page.getPageNum());
        orderSearchDTO.setPageSize(page.getPageSize());
        orderSearchDTO.setStatus(OrderStatus.SUCCESS.value());
        orderSearchDTO.setDeleteStatus(OrderDeleteStatus.NOT_DELETE.value());
        EsPageVO<EsOrderVO> esOrderVOEsPageVO = orderService.orderPage(orderSearchDTO);
        for (EsOrderVO esOrderVO : esOrderVOEsPageVO.getList()) {
            for (EsOrderItemVO orderItem : esOrderVO.getOrderItems()) {
                esOrderVO.setIsComm(orderItem.getIsComm());
                break;
            }
        }
        return ServerResponseEntity.success(esOrderVOEsPageVO);
    }

    /**
     * 取消订单
     */
    @PutMapping("/cancel/{orderId}")
    @Operation(summary = "根据订单号取消订单" , description = "根据订单号取消订单")
    @Parameter(name = "orderId", description = "订单号" , required = true)
    public ServerResponseEntity<String> cancel(@PathVariable("orderId") Long orderId) {
        Long userId = AuthUserContext.get().getUserId();
        Order order = orderService.getOrderByOrderIdAndUserId(orderId, userId);
        if (!Objects.equals(order.getStatus(), OrderStatus.UNPAY.value()) && !Objects.equals(order.getStatus(), OrderStatus.CLOSE.value())) {
            // 订单已支付，无法取消订单
            return ServerResponseEntity.showFailMsg("订单已支付，无法取消订单");
        }
        // 如果订单未支付的话，将订单设为取消状态
        orderService.cancelOrderAndGetCancelOrderIds(Collections.singletonList(order.getOrderId()));
        return ServerResponseEntity.success();
    }


    /**
     * 确认收货
     */
    @PutMapping("/receipt/{orderId}")
    @Operation(summary = "根据订单号确认收货" , description = "根据订单号确认收货")
    public ServerResponseEntity<String> receipt(@PathVariable("orderId") Long orderId) {
        Long userId = AuthUserContext.get().getUserId();
        Order order = orderService.getOrderByOrderIdAndUserId(orderId, userId);

        if (!Objects.equals(order.getStatus(), OrderStatus.CONSIGNMENT.value())) {
            if (Objects.equals(order.getStatus(), OrderStatus.SUCCESS.value())) {
                return ServerResponseEntity.showFailMsg("订单已收货，请刷新页面");
            } else {
                return ServerResponseEntity.showFailMsg("订单状态异常，请刷新后重试");
            }
        }
        if (Objects.equals(order.getRefundStatus(), RefundStatusEnum.APPLY.value())) {
            // 订单退款中，无法确认收货
            return ServerResponseEntity.showFailMsg("订单退款中，无法确认收货");
        }
        List<OrderItem> orderItems = orderItemService.listOrderItemsByOrderId(orderId);
        order.setOrderItems(orderItems);


        //注意：订单的确认收货是需要通知很多个服务的。
        // 在发送普通消息的时候，可能消息已经落地发送了，这边抛了异常，让数据回滚，变为未确认收货的状态，此时用户再点击退货，接着再次点击确认收货，
        // 而接收方确实是收到该消息，订单状态从 确认收货变成了“确认收货”，这两个确认收货的状态有本质的区别，所以应该让订单确确实实变为确认收货状态，再向各个服务推送消息
        // 因此用事务消息会比较好

        // 开启事务消息，通知订单自己，开始往各个服务发送通知了
        TransactionSendResult transactionSendResult = orderReceiptTemplate.sendMessageInTransaction(RocketMqConstant.ORDER_RECEIPT_TOPIC, new GenericMessage<>(orderId), null);

        if (!Objects.equals(transactionSendResult.getLocalTransactionState(), LocalTransactionState.COMMIT_MESSAGE)) {
            return ServerResponseEntity.fail(ResponseEnum.EXCEPTION);
        }
        esOrderFeignClient.updateOrder(orderId);
        return ServerResponseEntity.success();
    }

    /**
     * 删除订单
     */
    @DeleteMapping("/{orderId}")
    @Operation(summary = "根据订单号删除订单" , description = "根据订单号删除订单")
    @Parameter(name = "orderId", description = "订单号" , required = true)
    public ServerResponseEntity<String> delete(@PathVariable("orderId") Long orderId) {
        Long userId = AuthUserContext.get().getUserId();

        Order order = orderService.getOrderByOrderIdAndUserId(orderId, userId);

        if (!Objects.equals(order.getStatus(), OrderStatus.SUCCESS.value()) && !Objects.equals(order.getStatus(), OrderStatus.CLOSE.value()) ) {
            // 订单未完成或未关闭，无法删除订单
            return ServerResponseEntity.showFailMsg("订单未完成或未关闭，无法删除订单");
        }

        // 删除订单
        orderService.deleteOrder(order.getOrderId());
        esOrderFeignClient.updateOrder(orderId);
        return ServerResponseEntity.success();
    }

    @GetMapping("/get_order_item/{orderItemId}")
    @Operation(summary = "根据订单项id获取订单项详情" , description = "根据订单项id获取订单项详情")
    @Parameter(name = "orderItemId", description = "订单项号" , required = true)
    public ServerResponseEntity<OrderItemVO> getOrderItemById(@ParameterObject @PathVariable("orderItemId") Long orderItemId) {
        Long userId = AuthUserContext.get().getUserId();
        OrderItemVO orderItemVO = orderItemService.getByOrderItemId(orderItemId);
        if (userId == null || orderItemVO == null || !userId.equals(orderItemVO.getUserId())) {
            return ServerResponseEntity.showFailMsg("订单项错误");
        }
        return ServerResponseEntity.success(orderItemVO);
    }

    @GetMapping("/get_order_status")
    @Operation(summary = "根据虚拟订单编号获取订单券码")
    public ServerResponseEntity<OrderShopVO> getOrderStatus(@RequestParam("orderId") Long orderId) {
        EsOrderBO esorder = orderService.getEsOrder(orderId);
        Order order = mapperFacade.map(esorder, Order.class);
        OrderShopVO orderShopVO = new OrderShopVO();
        orderShopVO.setStatus(order.getStatus());
        orderShopVO.setRefundStatus(order.getRefundStatus());
        // 如果是虚拟商品订单，处理下虚拟商品订单相关数据
        if(Objects.equals(order.getOrderMold(),1)) {
            Long stationId = AuthUserContext.get().getTenantId();
            orderVirtualInfoService.handlerVirtualProdOrder(order, orderShopVO,stationId);
        }
        return ServerResponseEntity.success(orderShopVO);
    }
}
